package pso.tsp;

/**
 * 每一个粒子个体
 */
public class Unit {
    private int[] mPath;  //行走的城市路径，存储城市编号
    private int mFitness; //适应度值，为当前个体走这个路径的总距离。越小越好。

    public Unit(int[] path) {
        mPath = path;
        mFitness = calculateFitness();
    }

    public void printPath() {
        if (mPath == null) {
            System.out.println("mPath为null,当前个体的路径为空");
        } else {
            for (int i = 0; i < mPath.length - 1; i++) {
                System.out.print(CityLab.getInstance().getmCities().get(mPath[i]).getName() + "——》");
            }
            System.out.println(CityLab.getInstance().getmCities().get(mPath[mPath.length - 1]).getName());
        }
    }

    public void upDateFitness() {
        this.mFitness = calculateFitness();
    }

    /**
     * 计算当前路径的适应值，即为路径长度
     */
    public int calculateFitness() {
        //根据经纬度计算距离
        //近似计算：0.00001度，距离相差约1米；0.01，距离相差1000米.1度，距离相差100km
        int distance = 0;  //单位千米(km)
        int n = mPath.length;
        for (int i = 1; i < n; i++) {
            City c1 = CityLab.getInstance().getmCities().get(mPath[i - 1]);
            City c2 = CityLab.getInstance().getmCities().get(mPath[i]);
            distance += Math.sqrt(Math.pow(100 * (c1.getLatitude() - c2.getLatitude()), 2) + Math.pow(100 * (c1.getLongitude() - c2.getLongitude()), 2));
        }
        distance += Math.sqrt(Math.pow(100 * (CityLab.getInstance().getmCities().get(mPath[0]).getLatitude() - CityLab.getInstance().getmCities().get(mPath[n - 1]).getLatitude()), 2) + Math.pow(100 * (CityLab.getInstance().getmCities().get(mPath[0]).getLongitude() - CityLab.getInstance().getmCities().get(mPath[n - 1]).getLongitude()), 2));
        return distance;
    }

    public int[] getPath() {
        return mPath;
    }

    public void setPath(int[] path) {
        mPath = path;
    }

    public int getFitness() {
        return mFitness;
    }

    public void setFitness(int fitness) {
        mFitness = fitness;
    }
}
